﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CRM.Database.Model;
using DevExpress.Web.Mvc;
using DB = CRM.Models.DB;
using Utilites;
namespace CRM.Controllers
{
    [Localize]
    public class TDController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        #region CustomerTechnic - moved

        public ActionResult CustomerTechnicEdit(CRM.Database.Model.Customers customerItem)
        {
            return PartialView(customerItem);
        }

        public ActionResult TechnicRequestsList(CRM.Database.Model.Customers customerItem)
        {
            return PartialView(customerItem);
        }

        #endregion

        #region TechnicRequests - moved

        #region Общие действия для создания и редакрирования - moved

        public ActionResult TechnicRequestProductSystems(int key)
        {
            //вызов устается из DB
            var requestExt = DB.TechnicRequestExtDic[key];
            return PartialView(requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TechnicRequestProductSystemsAdd([ModelBinder(typeof(DevExpressEditorsBinder))] ProductSystems item, int key)
        {
            var productSystemsCol = new ProductSystemsCollection();
            //вызов устается из DB
            var requestExt = DB.TechnicRequestExtDic[key];
            if (requestExt != null)
            {
                var productSystem = (ProductSystems)productSystemsCol.GetItemById(item.IdProductSystem);
                //var productSystem = DB.GetProductSystembyId(item.IdProductSystem);
                if (productSystem != null)
                {
                    if (!requestExt.ProdustSystemsList.Contains(productSystem))
                        requestExt.ProdustSystemsList.Add(productSystem);
                }
            }
            return PartialView("TechnicRequestProductSystems", requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TechnicRequestProductSystemsDelete([ModelBinder(typeof(DevExpressEditorsBinder))] ProductSystems item, int key)
        {
            var productSystemsCol = new CRM.Database.Model.ProductSystemsCollection();
            //вызов устается из DB
            var requestExt = DB.TechnicRequestExtDic[key];
            if (requestExt != null)
            {
                var productSystem = (CRM.Database.Model.ProductSystems)productSystemsCol.GetItemById(item.IdProductSystem);
                //var productSystem = DB.GetProductSystembyId(item.IdProductSystem);
                if (productSystem != null)
                {
                    if (requestExt.ProdustSystemsList.Contains(productSystem))
                        requestExt.ProdustSystemsList.Remove(productSystem);
                }
            }
            return PartialView("TechnicRequestProductSystems", requestExt);
        }

        public ActionResult TechnicRequestLEPartial(int key)
        {
            //вызов устается из DB
            var requestExt = DB.TechnicRequestExtDic[key];
            return PartialView(requestExt);
        }

        public ActionResult TechnicRequestContactPartial(int key)
        {
            var idLegalEntity = (Request.Params["LE"] != null) ? int.Parse(Request.Params["LE"]) : -1;
            //вызов устается из DB
            var requestExt = DB.TechnicRequestExtDic[key];
            requestExt.IdLegalEntity = idLegalEntity;
            requestExt.Request.IdLegalEntity = idLegalEntity;
            return PartialView(requestExt);
        }

        public ActionResult TechnicRequestAddressesPartial(int key)
        {
            var idLegalEntity = (Request.Params["LE"] != null) ? int.Parse(Request.Params["LE"]) : -1;
            //вызов устается из DB
            var requestExt = DB.TechnicRequestExtDic[key];
            requestExt.IdLegalEntity = idLegalEntity;
            requestExt.Request.IdLegalEntity = idLegalEntity;
            return PartialView(requestExt);
        }

        #endregion

        #region Создание заявки менеджером - moved

        /// <summary>
        /// Новая заявка на выезд
        /// </summary>
        /// <param name="idCustomer"></param>
        /// <returns></returns>
        [HttpGet]
        [CheckAccessAttribute]
        public ActionResult TechnicRequestCreate(int idCustomer)
        {
            var customersCol = new CRM.Database.Model.CustomersCollection();
            var leCol = new CRM.Database.Model.LegalEntitiesCollection();
            var visitsTypesCol = new CRM.Database.Model.VisitsTypesCollection();
            var requestExt = new CRM.Database.Model.TechnicRequestsExt();

            //получение текущего клиента
            var customer = (CRM.Database.Model.Customers)customersCol.GetItemById(idCustomer);
            //var customer = DB.GetCustomerById(idCustomer);
            if (customer == null) return RedirectToAction("Index", "Customers");

            //заполнение ИД клиента
            requestExt.Request.IdCustomer = idCustomer;
            
            //заполнение ИД юр. лица
            if (customer.LegalEntities != null)
            {
                if (customer.LegalEntities.Count > 0)
                {
                    var legalEntity = leCol.GetFullDefinedLegalEntitiesByCustomerId(idCustomer).First();
                    //var legalEntity = DB.GetFullDefinedLegalEntitiesByCustomerId(idCustomer).FirstOrDefault();
                    if (legalEntity != null)
                    {
                        requestExt.IdLegalEntity = legalEntity.IdLegalEntity;
                        //заполнение ИД контакта
                        var contactsCol = new CRM.Database.Model.ContactsCollection();
                        var contact = contactsCol.GetFullDefinedContactsByLegalEntityId(requestExt.IdLegalEntity).First();
                        //var contact = DB.GetFullDefinedContactsByLegalEntityId(requestExt.IdLegalEntity).First();
                        if (contact != null)
                            requestExt.IdContact = contact.IdContact;
                        //заполнение ИД адреса
                        var address = legalEntity.Addresses.FirstOrDefault();
                        if (address != null)
                            requestExt.IdAddress = address.IdAddress;
                    }
                }
            }

            //заполнение начальной даты
            requestExt.Request.BeginDate = DateTime.Now;
            //заполнение конечной даты
            requestExt.Request.EndDate = DateTime.Now.AddDays(7);
            //подстановка типа выезда
            requestExt.VisitsTypes = ((CRM.Database.Model.VisitsTypes)visitsTypesCol.GetItemById(1)).VisitsType.ToString();
            //requestExt.VisitsTypes = DB.GetVisitsTypebyId(1).VisitsType.ToString();

            //сохранение заявки в словарь
            //новое - остается
            var key = DB.TechnicRequestExtDic.Count;
            requestExt.Key = key;
            //новое - остается
            DB.TechnicRequestExtDic.Add(key, requestExt);
            return View(requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TechnicRequestCreate([ModelBinder(typeof(DevExpressEditorsBinder))] TechnicRequestsExt requestNew)
        {
            var confCol = new ConfigurationsCollection();
            var visitsTypesCol = new VisitsTypesCollection();

            //получение заявки из словаря
            var requestExtResult = DB.TechnicRequestExtDic[requestNew.Key];
            //var requestExtResult = DB.TechnicRequestExtDictionary[requestNew.Key];

            //сохранение файлов с рандомным именами
            var files = UploadControlExtension.GetUploadedFiles("ucMultiFile");
            foreach (var fileItem in files)
            {
                if (fileItem == null) continue;
                if (string.IsNullOrEmpty(fileItem.FileName)) continue;
                var postedFileName = Path.GetFileName(fileItem.FileName);
                var fileExtention = postedFileName.Split('.').Last();
                var resultFileName = Guid.NewGuid() + "." + fileExtention;
                var filePath = confCol.TechnicAttachmentsPath;
                //var filePath = Configurations.TechnicAttachmentsPath;
                fileItem.SaveAs(Path.Combine(filePath, resultFileName));

                //запись информации о сохраненном файле в объект аттачмента
                var attachment = new TechnicRequestAttachments { Name = postedFileName, Path = filePath + "\\" + resultFileName };
                //var attachment = new TechnicRequestAttachments { Name = postedFileName, Path = filePath + "\\" + resultFileName };
                //добавление аттачмента к листу аттачментов расширенной заявки
                requestExtResult.AttachmentsList.Add(attachment);
            }

            //На этом этапе мы имеем расширенную заявку с добавленными аттачментами
            //Заполнение результирующей заявки полученными значениями
            requestExtResult.Request.IdTechnicRequest = -1;
            requestExtResult.Request.IdTechnicRequestStatus = 1;
            requestExtResult.Request.IdTechnic = 581;
            
            requestExtResult.Request.CreateDate = DateTime.Now;

            requestExtResult.Request.Comments = requestNew.Request.Comments;
            requestExtResult.Request.BeginDate = requestNew.Request.BeginDate;
            requestExtResult.Request.EndDate = requestNew.Request.EndDate;
            requestExtResult.Request.Comments = requestNew.Request.Comments;
            requestExtResult.VisitsTypes = requestNew.VisitsTypes;
            if (string.IsNullOrEmpty(requestExtResult.VisitsTypes))
                requestExtResult.VisitsTypes = ((VisitsTypes)visitsTypesCol.GetItemById(1)).VisitsType.ToString();
                //requestExtResult.VisitsTypes = DB.GetVisitsTypebyId(1).VisitsType.ToString();

            requestExtResult.Request.IdLegalEntity = requestNew.IdLegalEntity;
            requestExtResult.Request.IdContact = requestNew.IdContact;
            requestExtResult.Request.IdAddress = requestNew.IdAddress;


            //добавление списка с оборудованием
            var result1 = requestExtResult.FillEquipmentsListFromCustomer();

            //сохранение расширенной заявки в базу
            var result = requestExtResult.Add(Request.LogonUserIdentity.Name);
            
            result = requestExtResult.Update(Request.LogonUserIdentity.Name);

            DB.TechnicsSendNewMail(requestExtResult.Request);

            return RedirectToAction("Index", "Customers");
        }


        ///// <summary>
        ///// Отправить уведомление о получении заявки контактному лицу
        ///// типы заявок: плановая
        ///// получатели: контактное лицо
        ///// шаблон: 
        ///// </summary>
        ///// <param name="idTrainingsRequest"></param>
        ///// <returns></returns>
        //public ActionResult TrainingsRequestSendNewMail(int idTrainingsRequest)
        //{

        //    var confCol = new ConfigurationsCollection();
        //    var requestsCol = new TrainingsRequestsCollection();

        //    //остается вызов из DB
        //    var paramsList = DB.GetDocReportParamsByRequestId(idTrainingsRequest);
        //    if (paramsList != null)
        //    {
        //        var targetFilePath = confCol.TrainingsDocsTargetPath + "\\" + "new" + idTrainingsRequest;
        //        var sourceFilePath = confCol.TrainingsNewRequestFilePath;
        //        DocReport.CreateDoc(sourceFilePath, targetFilePath, paramsList);

        //        var request = (TrainingsRequests)requestsCol.GetItemById(idTrainingsRequest);
        //        //var request = DB.GetTrainingsRequestesById(idTrainingsRequest);
        //        if (request != null)
        //        {
        //            if (request.IsPlanned)
        //            {
        //                var log = DB.TrainingsSendNewMail(request);
        //                //var log = request.SendNewMail();)
        //                if (string.IsNullOrEmpty(log))
        //                {
        //                    request.DateOfRegisterMail = DateTime.Now;
        //                    requestsCol.Update(request, Request.LogonUserIdentity.Name);
        //                    //DB.TrainingsRequestsUpdate(request);
        //                }
        //            }
        //        }
        //    }
        //    return RedirectToAction("TrainingsRequestDetails", new { idTrainingsRequest });
      //  }

        #endregion

        #region Отображение списка заявок - moved

        /// <summary>
        /// Заявки на выезды
        /// </summary>
        /// <returns></returns>
        [CheckAccessAttribute]
        public ActionResult TechnicRequests()
        {
          //  var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            return View();
            //return View(DB.TechnicRequests.OrderByDescending(p => p.IdTechnicRequest));
        }

        public ActionResult TechnicRequestsPartial()
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            return PartialView(requestsCol.TechnicRequestsList);
            //return PartialView(DB.TechnicRequests.OrderByDescending(p => p.IdTechnicRequest));
        }

        public ActionResult CustomerTechnicRequestsPartial(int idCustomer)
        {
            var custCol = new CustomersCollection();
            var cust = custCol.GetItemById(idCustomer) as Customers;

            return PartialView("TechnicRequestsList", cust);
        }

        #endregion

        #region Удаление заявки - moved

        [HttpPost, ValidateInput(false)]
        public ActionResult TechnicRequestsPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] CRM.Database.Model.TechnicRequests item)
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            var request = (CRM.Database.Model.TechnicRequests)requestsCol.GetItemById(item.IdTechnicRequest);
            //var request = DB.GetTechnicRequestById(item.IdTechnicRequest);
            if (request != null)
            {
                requestsCol.Delete(request);
                //request.Delete();
            }
            return PartialView("TechnicRequestsPartial", requestsCol.TechnicRequestsList.OrderByDescending(p => p.IdTechnicRequest).ToList());
            //return PartialView("TechnicRequestsPartial", DB.TechnicRequests.OrderByDescending(p => p.IdTechnicRequest));
        }

        #endregion

        #region Отображение заявки на чтение - moved

        /// <summary>
        /// отображение деталей заявки
        /// </summary>
        /// <returns></returns>
        [CheckAccessAttribute]
        public ActionResult TechnicRequestDetails(int idTecnicRequest)
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            var request = (CRM.Database.Model.TechnicRequests)requestsCol.GetItemById(idTecnicRequest);
            //var request = DB.GetTechnicRequestById(idTecnicRequest);
            if (request == null) return RedirectToAction("TechnicRequests");
            return View(request);
        }

        /// <summary>
        /// частичное отображение списка обородования в заявке
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public ActionResult TechnicRequestsEquipmentsPartial(int idRequest)
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            var request = (CRM.Database.Model.TechnicRequests)requestsCol.GetItemById(idRequest);
            //var request = DB.GetTechnicRequestById(idRequest);
            return request == null ? PartialView() : PartialView(request);
        }

        /// <summary>
        /// частичное отображение аттачментов
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public ActionResult TechnicRequestsAttachmentsPartial(int idRequest)
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            var request = (CRM.Database.Model.TechnicRequests)requestsCol.GetItemById(idRequest);
            //var request = DB.GetTechnicRequestById(idRequest);
            return request == null ? PartialView() : PartialView(request);
        }

        /// <summary>
        /// Частичное отображение систем
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public ActionResult TechnicRequestsProductSystemsPartial(int idRequest)
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            var request = (CRM.Database.Model.TechnicRequests)requestsCol.GetItemById(idRequest);
            //var request = DB.GetTechnicRequestById(idRequest);
            return request == null ? PartialView() : PartialView(request);
        }

        /// <summary>
        /// частичное отображение типов выездов
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public ActionResult TechnicRequestsVisitsTypesPartial(int idRequest)
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            var request = (CRM.Database.Model.TechnicRequests)requestsCol.GetItemById(idRequest);
            //var request = DB.GetTechnicRequestById(idRequest);
            return request == null ? PartialView() : PartialView(request);
        }

        #endregion

        #region Редактирование заявки - moved

        [HttpGet]
        public ActionResult TechnicRequestEdit(int idRequest)
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();

            //получение заявки по ИД
            var request = (CRM.Database.Model.TechnicRequests)requestsCol.GetItemById(idRequest);
            //var request = DB.GetTechnicRequestById(idRequest);
            if (request == null) return RedirectToAction("TechnicRequests");

            //создание и заполнение расширенной заявки
            var requestExt = new CRM.Database.Model.TechnicRequestsExt();
            requestExt.Fill(request);

            //сохранение заявки в словарь
            var key = DB.TechnicRequestExtDic.Count;
            requestExt.Key = key;
            DB.TechnicRequestExtDic.Add(key, requestExt);

            return View(requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TechnicRequestEdit([ModelBinder(typeof(DevExpressEditorsBinder))] TechnicRequestsExt requestNew)
        {
            var confCol = new ConfigurationsCollection();

            //получение заявки из словаря
            var requestExtResult = DB.TechnicRequestExtDic[requestNew.Key];
            if (requestExtResult == null) return RedirectToAction("TechnicRequests");

            //заполнение результирующей заявки
            requestExtResult.FillForResult(requestNew);

            //сохранение файлов с рандомным именами
            var files = UploadControlExtension.GetUploadedFiles("ucMultiFile");
            foreach (var fileItem in files)
            {
                if (fileItem == null) continue;
                if (string.IsNullOrEmpty(fileItem.FileName)) continue;
                var postedFileName = Path.GetFileName(fileItem.FileName);
                var fileExtention = postedFileName.Split('.').Last();
                var resultFileName = Guid.NewGuid() + "." + fileExtention;
                var filePath = confCol.TechnicAttachmentsPath;
                fileItem.SaveAs(Path.Combine(filePath, resultFileName));

                //запись информации о сохраненном файле в объект аттачмента
                var attachment = new TechnicRequestAttachments
                                     {Name = postedFileName, Path = filePath + "\\" + resultFileName};
                //добавление аттачмента к листу аттачментов расширенной заявки
                requestExtResult.AttachmentsList.Add(attachment);
            }

            //обновление расширенной заявки в базе
            var result = requestExtResult.Update(Request.LogonUserIdentity.Name);
            //DB.TechnicRequestExtUpdate(requestExtResult);)

            return RedirectToAction("TechnicRequestDetails", new {idTecnicRequest = requestExtResult.Request.IdTechnicRequest});
        }

        public ActionResult TechnicRequestsEquipments(int key)
        {
            var requestExt = DB.TechnicRequestExtDic[key];
            return PartialView(requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TechnicRequestsEquipmentsAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TechnicRequestsEquipments item, int key)
        {
            var bindingsCol = new CRM.Database.Model.CustomersEquipmentsCollection();
            var equpmentsCol = new CRM.Database.Model.EquipmentsCollection();

            var requestExt = DB.TechnicRequestExtDic[key];
            if (requestExt != null)
            {
                var equpment = (CRM.Database.Model.Equipments)equpmentsCol.GetItemById(item.IdEquipment);
                //var equpment = DB.GetEquipmentbyId(item.IdEquipment);
                if (equpment != null)
                {
                    if (!(requestExt.Contains(item)))
                    {
                        var bindingItem = new CRM.Database.Model.TechnicRequestsEquipments
                                              {
                                                  IdEquipment = equpment.IdEquipment,
                                                  IdTechnicRequest = requestExt.Request.IdTechnicRequest,
                                                  EquipmentCount = 0,
                                                  IssueDate = DateTime.Now.Date
                                              };

                        var customerEqupmentItem = bindingsCol.GetCustomersEquipmentsbyIdCustomerAndIdEquipment(requestExt.Request.IdCustomer, item.IdEquipment);
                        //var customerEqupmentItem = DB.GetCustomersEquipmentsbyIdCustomerAndIdEquipment(requestExt.Request.IdCustomer, item.IdEquipment);
                        if (customerEqupmentItem != null)
                        {
                            bindingItem.EquipmentCount = customerEqupmentItem.EquipmentCount;
                            bindingItem.IssueDate = customerEqupmentItem.IssueDate;
                        }
                        requestExt.RequestsEquipmentsList.Add(bindingItem);
                    }
                }
            }
            return PartialView("TechnicRequestsEquipments", requestExt);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult TechnicRequestsEquipmentsDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TechnicRequestsEquipments item, int key)
        {
            var requestExt = DB.TechnicRequestExtDic[key];
            if (requestExt != null)
            {
                requestExt.DeleteEquipment(item);
            }
            return PartialView("TechnicRequestsEquipments", requestExt);
        }

        #endregion

        #region Отчеты - moved

        /// <summary>
        /// Отчеты
        /// </summary>
        /// <returns></returns>
        [CheckAccessAttribute]
        public ActionResult TechnicReports()
        {
            return View();
        }

        /// <summary>
        /// Формирование отчета и сохранения его во вложениях заявки
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public ActionResult MakeReport(int idRequest)
        {
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            var confCol = new CRM.Database.Model.ConfigurationsCollection();
            var equipmentsCol = new CRM.Database.Model.EquipmentsCollection();

            //текущий пользователь
            var currentUser = Request.LogonUserIdentity.Name;

            var request = (TechnicRequests)requestsCol.GetItemById(idRequest);
            //var request = DB.GetTechnicRequestById(idRequest);
            if (request == null) return RedirectToAction("TechnicRequestDetails", new {idTecnicRequest = idRequest});

            var templateFileName = confCol.TechnicDocsTemplatesPath + "//" + "ReportTemplateTitle.docx";
            var titleFileName = confCol.TechnicDocsReportsPath + "\\" + request.IdTechnicRequest.ToString() + "title.docx";

            //получить заполненные закладки для титульного листа
            var bookmarksList = DB.GetTechnicBookmarksListByRequest(request);

            //получение списка оборудования в заявке
            var equpmentList = equipmentsCol.GetEquipmentsListByRequestId(request.IdTechnicRequest);
            //var equpmentList = DB.GetEquipmentsListByRequestId(request.IdTechnicRequest);

            var equipmentTable = request.EquipmentReportTable;
            //var equipmentTable = DB.GenerateEquipmentReportTableByRequest(request);

            //формирование и сохранение файла отчета
            Utilites.DocReport.TechnicReportTitle(templateFileName, titleFileName, bookmarksList, equipmentTable);

            //добавить файл в список вложений заявки
            request.UpdateAttachment(Resourses.Resourses.TechnicTitleList, titleFileName, Request.LogonUserIdentity.Name);

            //создать полный отчет
            Utilites.DocReport.Merge(new[] {titleFileName},
                                     confCol.TechnicDocsReportsPath + "\\" + idRequest + "BlankReport.docx",
                                     true,
                                     confCol.TechnicDocsTemplatesPath + "\\" + "ReportTemplateSecondPart.docx");

            //добавить полный отчет в список заявок
            request.UpdateAttachment("Отчет для заполнения", confCol.TechnicDocsReportsPath + "\\" + idRequest + "BlankReport.docx", Request.LogonUserIdentity.Name);

            return RedirectToAction("TechnicRequestDetails", new {idTecnicRequest = idRequest});
            //Utilites.DocReport.Merge(new[] { filepath + "2.doc" }, filepath + "3.doc", true, filepath + "1.doc");
            ////////---------------------------------------------------------------------------------
            //var newTechRequestCol = new CRM.Database.Model.TechnicRequestCollection();
            //CRM.Database.Model.TechnicRequests newDatabaseRequest = newTechRequestCol.GetItemById(idRequest) as Database.Model.TechnicRequests;

            //if (newDatabaseRequest != null)
            //{
            //    var result = newDatabaseRequest.createasJKB(null, currentUser);
            //}
            /////////////-----------------------------------------------------------------------------
        }

        /// <summary>
        /// анализирует вложенный отчет. Если отчета нет - кидает на страницу для вложения отчета
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public ActionResult AnalyseReport(int idRequest)
        {
            //текущий пользователь
            var currentUser = Request.LogonUserIdentity.Name;
            //получить коллекцию заявок
            var requestsCollection = new TechnicRequestsCollection();
            //получить заявку 
            var request = requestsCollection.GetItemById(idRequest) as TechnicRequests;
            if (request == null) return View("TechnicError");

            //получить заполненный отчет в виде вложения, или отправить на страницу загрузки отчета
            var attachment = request.GetCompletedReportAttachment();
            if (attachment == null)
                return RedirectToAction("InsertCompletedReport", new {idRequest});
            
            //анализирование отчета
            if(!Utilites.DocReport.TechnicReportAnalyse(attachment, currentUser))
                return View("TechnicError");

            return RedirectToAction("ViewReport", new { idRequest });
            //return View(request);
        }

        /// <summary>
        /// вложение заполненного отчета
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public ActionResult InsertCompletedReport(int idRequest)
        {
            //получить коллекцию заявок
            var requestsCollection = new TechnicRequestsCollection();
            //получить заявку 
            var request = requestsCollection.GetItemById(idRequest) as TechnicRequests;
            if (request == null) return View("TechnicError");
            return View(request);
        }

        [HttpPost, ValidateInput(false)]
        public ActionResult InsertCompletedReport(HttpPostedFileBase fileUpload, [ModelBinder(typeof(DevExpressEditorsBinder))] TechnicRequests request)
        {
            var confCol = new ConfigurationsCollection();

            if (fileUpload == null || request == null) return View("TechnicError");
            //текущий пользователь
            var currentUser = Request.LogonUserIdentity.Name;
            //получить коллекцию заявок
            var requestsCollection = new TechnicRequestsCollection();
            //получить заявку 
            request = requestsCollection.GetItemById(request.IdTechnicRequest) as TechnicRequests;
            if (request == null) return View("TechnicError");
            //проверка типа файла
            if(!Utilites.FileUtilites.ValidateExtention(fileUpload, "DOC") && 
                !Utilites.FileUtilites.ValidateExtention(fileUpload, "DOCX"))
                    return View("TechnicError");
            //сохранение файла
            var reportName = request.IdTechnicRequest + "CompletedReport." + Utilites.FileUtilites.GetFileExtention(fileUpload);
            var attachmentPath = Utilites.FileUtilites.SaveUplodedFile(fileUpload, reportName, confCol.TechnicDocsReportsPath);
            if (string.IsNullOrEmpty(attachmentPath)) return View("TechnicError");
            
            //добавление аттачмента к заявке, если такого аттачмента нет
            var attachmentsCollection = new TechnicRequestAttachmentsCollection();
            var idAttachment = attachmentsCollection.GetIdByPath(attachmentPath);
            if (idAttachment > 0) return RedirectToAction("AnalyseReport", new { idRequest = request.IdTechnicRequest });
            var attachment = new TechnicRequestAttachments
                                 {
                                     IdTechnicRequest = request.IdTechnicRequest,
                                     Name = Resourses.Resourses.TechnicCompletedReportAttachmentName,
                                     Path = attachmentPath
                                 };
            attachmentsCollection.Add(attachment, currentUser);
            //возвращение в дествие анализа отчета
            return RedirectToAction("AnalyseReport", new {idRequest = request.IdTechnicRequest});
        }

        /// <summary>
        /// просмотр вложенного отчета
        /// </summary>
        /// <param name="idRequest"></param>
        /// <returns></returns>
        public ActionResult ViewReport(int idRequest)
        {
            //текущий пользователь
            var currentUser = Request.LogonUserIdentity.Name;
            //получить коллекцию заявок
            var requestsCollection = new CRM.Database.Model.TechnicRequestsCollection();
            //получить заявку 
            var request = requestsCollection.GetItemById(idRequest) as CRM.Database.Model.TechnicRequests;
            if(request==null) return View("TechnicError");

            return View(request);
        }

        #endregion

        #region мои заявки - moved

        [CheckAccessAttribute]
        public ActionResult TechnicMyRequests()
        {
            return View();
        }

        public ActionResult TechnicMyRequestsPartial()
        {
            var userLogin = Request.LogonUserIdentity.Name;
            var usersCol = new UsersCollection();
            var requestsCol = new CRM.Database.Model.TechnicRequestsCollection();
            var user = usersCol.GetUserByLogin(userLogin);// DB.GetUserByLogin(userLogin);
            return PartialView(requestsCol.GetRequestsByUser(user).OrderByDescending(p => p.IdTechnicRequest).ToList());
            //return PartialView(DB.GetTechnicRequestsByUser(user).OrderByDescending(p => p.IdTechnicRequest));
        }

        #endregion

        #endregion

        #region TechnicRequestStatuses - moved

        [CheckAccessAttribute]
        public ActionResult TechnicRequestStatuses()
        {
            var statusesCol = new CRM.Database.Model.TechnicRequestStatusesCollection();
            return View(statusesCol.TechnicRequestStatusesList);
            //return View(DB.TechnicRequestStatuses);
        }

        public ActionResult TechnicRequestStatusesPartial()
        {
            var statusesCol = new CRM.Database.Model.TechnicRequestStatusesCollection();
            return PartialView("TechnicRequestStatusesPartial", statusesCol.TechnicRequestStatusesList);
            //return PartialView("TechnicRequestStatusesPartial", DB.TechnicRequestStatuses);
        }

        //[HttpPost, ValidateInput(false)]
        //public ActionResult TechnicRequestStatusesPartialUpdate([ModelBinder(typeof(DevExpressEditorsBinder))] TechnicRequestStatuses trainingRequestsStatusItem)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        DB.TechnicRequestStatusesUpdate(trainingRequestsStatusItem);
        //    }
        //    return PartialView("TechnicRequestStatusesPartial", DB.TechnicRequestStatuses);
        //}

        //[HttpPost, ValidateInput(false)]
        //public ActionResult TechnicRequestStatusesPartialDelete([ModelBinder(typeof(DevExpressEditorsBinder))] TechnicRequestStatuses trainingRequestsStatusItem)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        DB.TechnicRequestStatusesDelete(trainingRequestsStatusItem);
        //    }
        //    return PartialView("TechnicRequestStatusesPartial", DB.TechnicRequestStatuses);
        //}

        //[HttpPost, ValidateInput(false)]
        //public ActionResult TechnicRequestStatusesPartialAdd([ModelBinder(typeof(DevExpressEditorsBinder))] TechnicRequestStatuses trainingRequestsStatusItem)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        DB.TechnicRequestStatusesInsert(trainingRequestsStatusItem);
        //    }
        //    return PartialView("TechnicRequestStatusesPartial", DB.TechnicRequestStatuses);
        //}

        #endregion

        #region TechnicScheduler - moved

        /// <summary>
        /// календарь техников
        /// </summary>
        /// <returns></returns>
        [CheckAccessAttribute]
        public ActionResult TechnicScheduler()
        {
         //   return View(CRM.Database.Model.SchedulerDataObject.TechnicSchedulerObject);
            return View();
        }

        public ActionResult TechnicSchedulerPartial()
        {
            return PartialView(SchedulerDataObject.TechnicSchedulerObject);
        //    return PartialView(new SchedulerDataObject());
        }

        #endregion
    }
}